package cn.tedu._08security.base.config;

import cn.tedu._08security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * EnableGlobalMethodSecurity注解:
 * 1.Spring Security的注解;
 * 2.激活鉴权功能;
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig {

    /**
     * 创建UserDetailsService对象放到IoC容器中
     */
    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/api/public/**").permitAll()//不需要认证
                        .anyRequest().authenticated()//需要认证
                )
                //登录相关的请求不需要认证
                .formLogin(form -> form
                        .permitAll()
                )
                //注销相关的请求不需要认证
                .logout(logout -> logout
                        .permitAll()
                );
        return http.build();
    }
}
